//
//  DeviceListCell.m
//  OST
//
//  Created by mac on 13-7-6.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "MeterListCell.h"
#import "PersistableInfo.h"
#import "Utitlity.h"

@implementation MeterListCell
@synthesize labelName,icon;
@synthesize labelMeter;
@synthesize data;
@synthesize power;

-(void)initView
{
    UIImage *img1  = [UIImage imageNamed:@"bg_cell"];
    UIImage *img2  = [UIImage imageNamed:@"bg_cell_sel"];
    
    UIImageView *cellbg1 = [[UIImageView alloc]initWithImage:img1];
    UIImageView *cellbg2 = [[UIImageView alloc]initWithImage:img2];
    
    self.backgroundView = cellbg1;
    self.selectedBackgroundView = cellbg2;
}

-(void)setStatusData:(NSDictionary *)valDict
{
    power = [[valDict objectForKey:@"W"] floatValue];
    //NSString *unit = [valDict objectForKey:@"unit"];
    NSInteger wVal = [[valDict objectForKey:@"W"] integerValue];
    
    labelMeter.text =  [NSString stringWithFormat:@"%dW", wVal];
}

#pragma mark -
-(void)updateIcon
{
    PersistableInfo *info = [MeterListCell getMeterInfo:self.data];
    
    self.icon.image = [UIImage imageNamed:info.icon];
    
    if ([info.icon isEqualToString:@"icon_ammeter"] ||[info.icon isEqualToString:@"icon_camera"]||[info.icon isEqualToString:@"sur_0"]||[info.icon isEqualToString:@"sur_1"]||[info.icon isEqualToString:@"sur_2"])
    {
        self.icon.image = [UIImage imageNamed:info.icon];
    }
    else
    {
        self.icon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@close",info.icon]];
    }
    
    self.labelName.text = [self.data objectForKey:@"Alias"];

}

- (void)setMCellData:(NSDictionary *)theData
{
    if (self.data != theData )
    {
        self.data = theData;
    }
    [self updateIcon];
}

+(PersistableInfo *)getMeterInfo:(NSDictionary *)mdata
{
    NSString *uuid = [[mdata objectForKey:@"uuid"] lowercaseString];
    
    PersistableInfo *info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where uuid='%@'",uuid];
    if (!info) {
        info = [[PersistableInfo alloc]init];
        
        NSInteger deviceType = [[mdata objectForKey:@"DeviceType"] integerValue];
        if (deviceType == 5)
        {
            info.icon= @"icon_ammeter";
        }
        info.uuid = uuid;
        info.zid = [mdata objectForKey:@"ZID"];
        info.name = [mdata objectForKey:@"Alias"];
        [info save];

    }
    
    return info;
}

- (IBAction)changeMInfo:(id)sender
{
    if (self.delegate)
    {
        [self.delegate changeMeterInfo:self.data cell:self];
    }
}

@end
